//
//  HomeViewController.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/5/28.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeSearchNaviView.h"
#import "HomeHeadReusableView.h"
#import "productCellectionCell.h"
#import "ProductDetailViewController.h"

@interface HomeViewController () <
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>{
    
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
    
}

@property (nonatomic, strong) HomeSearchNaviView *naviView;

@property (nonatomic, strong) HomeHeadReusableView *homeHeadView;

@property (nonatomic , strong) UICollectionView *homeCollectionView;

@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) NSMutableArray <ProductItemModel *>*productDataArray;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self prepareData];
    [self requestData];
    [self initView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change) name:UIDeviceOrientationDidChangeNotification object:nil];
    
} 

- (void)prepareData {
    
    self.pageSize = 48;
    self.pageNum = 1;
    
    self.bannerArray = @[].mutableCopy;
    self.productDataArray = @[].mutableCopy;
}

- (void)requestData {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_INDEX_API];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:@(self.pageSize) forKey:@"pageSize"];
    [param setValue:@(self.pageNum) forKey:@"pageNum"];

    WEAKSELF
    [TTHttpManager getRequestWithUrl:url TimeOut:10.0 GetData:param FinishBlock:^(id  _Nonnull data) {

        BOOL fail = [[data valueForKey:@"code"] boolValue];
        if (!fail) {
            NSDictionary *resultDic = [data valueForKey:@"data"];
            NSDictionary *goodsDic = [resultDic valueForKey:@"goods"];
            
            NSInteger count = [[goodsDic valueForKey:@"count"] integerValue];
            if (count < weakSelf.pageSize) {
                weakSelf.homeCollectionView.mj_footer.state = MJRefreshStateNoMoreData;
            }
            
            for (NSDictionary *goodInfo in [goodsDic valueForKey:@"result"]) {
                ProductItemModel *model = [[ProductItemModel alloc] init];
                model.name = [goodInfo valueForKey:@"name"];
                model.path = [goodInfo valueForKey:@"path"];
                model.price = [goodInfo valueForKey:@"price"];
                model.productID = [goodInfo valueForKey:@"id"];
                [weakSelf.productDataArray addObject:model];
            }
            [weakSelf.homeCollectionView reloadData];
        }
        
        [weakSelf.homeCollectionView.mj_header endRefreshing];
        [weakSelf.homeCollectionView.mj_footer endRefreshing];
        

    } FailedBlock:^(NSError * _Nonnull error) {

        [weakSelf.homeCollectionView.mj_header endRefreshing];
        [weakSelf.homeCollectionView.mj_footer endRefreshing];
    }];
}

- (void)prepareTestData {
    
    for (int i = 0;i< 10;i++) {
        
        ProductItemModel *model = [[ProductItemModel alloc] init];
        model.name = @"666";
        model.path = @"";
        model.price = @"888888";
        model.productID = @"1234";
        [self.productDataArray addObject:model];
    }
}

- (void)initView {
    
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    CGFloat width = self.view.frame.size.width - tabbarWidth;
    CGFloat height = self.view.frame.size.height;
    
    CGFloat cellWidth;
    CGFloat distance = 5;
    if (width > height) {
        cellWidth = width/4 - 2*distance;
    } else {
        cellWidth = width/3 - 2*distance;
    }
    _cellSize =  CGSizeMake(cellWidth, cellWidth/0.7);
    _collectionEdge = UIEdgeInsetsMake(distance, distance, distance, distance);
    
    self.view.backgroundColor = UIColorHex(0xF1F1F1);

//    [self.view addSubview:self.naviView];
    
    [self.view addSubview:self.homeCollectionView];
    
//    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_equalTo(self.view);
//        make.height.mas_equalTo([TT_SizeHelper getGlobalNavigationBarHeoght]);
//        make.top.mas_equalTo(0);
//    }];
    
    [self.homeCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view);
    }];
}

- (HomeSearchNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[HomeSearchNaviView alloc] init];
    }
    return _naviView;
}

- (UICollectionView *)homeCollectionView {
    if (!_homeCollectionView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.headerReferenceSize = CGSizeMake(TTScreenWidth, TTScreenWidth * homeBannerRatio);
        _homeCollectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _homeCollectionView.delegate = self;
        _homeCollectionView.dataSource = self;
        _homeCollectionView.backgroundColor = UIColorHex(0xf1f1f1);
        [_homeCollectionView registerNib:[UINib nibWithNibName:@"productCellectionCell" bundle:nil] forCellWithReuseIdentifier:@"productCellectionCell"];
        
        [_homeCollectionView registerClass:[HomeHeadReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeadReusableView"];
        
        WEAKSELF
        _homeCollectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf prepareData];
            [weakSelf requestData];
        }];
        
        _homeCollectionView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf requestData];
        }];
    }
    return _homeCollectionView;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
          viewForSupplementaryElementOfKind:(NSString *)kind
                                atIndexPath:(NSIndexPath *)indexPath {
    
    self.homeHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeadReusableView" forIndexPath:indexPath];

    [self.homeHeadView configBannerCellWithModel:self.bannerArray ImgClickedBlock:^(NSInteger index) {
        
    }];

    return self.homeHeadView;
}

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.productDataArray.count > indexPath.row) {
        ProductDetailViewController *productDetail = [[ProductDetailViewController alloc] init];
        productDetail.productID = self.productDataArray[indexPath.row].productID;
        [self.navigationController pushViewController:productDetail animated:YES];
    }

}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView
                                   cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    productCellectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"productCellectionCell" forIndexPath:indexPath];

    [cell fillCellWithModel:self.productDataArray[indexPath.row]];
    
    return cell;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return self.productDataArray.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return _cellSize;
}

//设置cell的位置
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section
{
        return _collectionEdge;
}

- (void)change
{
//    _cellSize =[self getCellSizeWithWidth:self.view.frame.size.height + 20];//加上状态栏高度
//    _collectionEdge = UIEdgeInsetsMake(1, 1, 1, 1);
//    [self.homeCollectionView reloadData];
}


- (CGSize)getCellSizeWithWidth:(CGFloat)width {
    
    CGFloat cellWidth;
    
    CGFloat screenW = self.view.frame.size.width ;
    CGFloat screenH = self.view.frame.size.height - tabbarWidth;
    CGFloat distance = 5;
    if (screenW > screenH) {
        cellWidth = screenH/3 - 2 * distance;
        
    } else {
        cellWidth = screenH/4 - 2 * distance;
    }
    return  CGSizeMake(cellWidth, cellWidth/0.7);
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    
    return  CGSizeMake(TTScreenWidth, TTScreenWidth * homeBannerRatio);
}

-(NSMutableArray *)bannerArray {
    
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray new];
        _bannerArray = @[
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487496514&di=6df642c7fcd416eee9723a1f0fe0af36&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fphotoblog%2F1202%2F13%2Fc0%2F10410979_10410979_1329065644468.jpg",
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487496514&di=45599a6107318bd383449fb885da919f&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fphotoblog%2F1410%2F07%2Fc4%2F39353741_39353741_1412674956971.jpg",
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487496511&di=1841cfb8db9ddf1f502d7385f1faa242&imgtype=0&src=http%3A%2F%2Fpic7.nipic.com%2F20100429%2F1412106_092608578069_2.jpg",
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487536585&di=1701f9990626982945c2a5b6edadcccd&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fphotoblog%2F1308%2F19%2Fc3%2F24648996_24648996_1376926604453.jpg",
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487536580&di=434bf1c1f8101427d671f180311e7fa1&imgtype=0&src=http%3A%2F%2Fpic43.nipic.com%2F20140711%2F52770_200417958000_2.jpg",
                         @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559487536579&di=612c1f506dbd449147fb23d018a2fbfd&imgtype=0&src=http%3A%2F%2Fimg8.zol.com.cn%2Fbbs%2Fupload%2F22979%2F22978191.JPG"
                         ].mutableCopy;
    }
    return _bannerArray;
}

@end
